import { ref, watch } from 'vue'
import { defineStore } from 'pinia'
import { getBaseWeatherByAdcode } from '@/api/index.js'

// 使用 Pinia 定义一个名为 'weather' 的状态管理 store
export const WeatherStore = defineStore('weather', () => {
  // 定义状态
  const cityWeatherList = ref([])

  // 定义方法
  const addCityWeather = (obj) => {
    cityWeatherList.value.push(obj)
  }
  const removeCityWeather = (value) => {
    cityWeatherList.value = cityWeatherList.value.filter((item) => item.adcode !== value)
  }
  // 数据持久化
  const getCityWeatherList = async () => {
    // 从 localStorage 获取数据
    const storedData = localStorage.getItem('cityWeatherList')
    const savedCityWeatherList = storedData ? JSON.parse(storedData) : []
    // 使用 async/await 获取每个城市的最新天气信息
    const updatedCityWeatherList = await Promise.all(
      savedCityWeatherList.map(async (item) => {
        // 获取最新天气数据，传入城市的 adcode
        const latestWeather = await getBaseWeatherByAdcode(item.adcode)
        return {
          ...item, // 保留原有的城市信息
          temperature: latestWeather.lives[0].temperature, // 用最新的天气数据覆盖
        }
      })
    )
    // 更新城市天气列表
    cityWeatherList.value = updatedCityWeatherList
  }
  watch(
    cityWeatherList,
    () => {
      localStorage.setItem('cityWeatherList', JSON.stringify(cityWeatherList.value))
    },
    { deep: true }
  )

  return {
    cityWeatherList,
    addCityWeather,
    removeCityWeather,
    getCityWeatherList,
  }
})
